#!/usr/bin/ruby
# Based on code by Brian Amberg
# http://ruby.brian-amberg.de/quiz/roman/ 

module RomanNumerals
    # Used for Integer to Roman conversion. (#roman)
  ROMAN_VALUES_ASSOC = %w(I IV V IX X XL L XC C CD D CM M).zip([1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000]).reverse
    # Used for Roman to Integer conversion. (Integer#roman)
  ROMAN_VALUES = ROMAN_VALUES_ASSOC.inject({}) { |h, (r,a)| h[r] = a; h }
  def self.extended(base)
    base.extend(ClassMethods) 
  end
  
  module ClassMethods
    # Returns a roman number string
    def Integer.roman(roman)
      last = roman[-1,1]
      roman.reverse.split('').inject(0) { | result, c |
        if ROMAN_VALUES[c] < ROMAN_VALUES[last]
          result -= ROMAN_VALUES[c]
        else
          last = c
          result += ROMAN_VALUES[c]
        end
      }
    end
  end
  
  # Spits out the number as a roman number
  def roman
    return "-#{(-self).roman}" if self < 0
    return "" if self == 0
    ROMAN_VALUES_ASSOC.each do | (i, v) | return(i+(self-v).roman) if v <= self end
  end

  
end